package com.wish.nettymarshalling;

import com.wish.common.MyUtils;
import com.wish.nettywithpack.NettyRobotServerWithPack;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;


/**
 * 暂时未实现，后续有时间再实现
 *
 * @author tantexian
 * @since 2016/7/18
 */
public class SubReqServer {

    public static void main(String[] args) {
        final int port = args.length >= 1 ? Integer.parseInt(args[0]) : MyUtils.getDefaultPort();
        try {
            new NettyRobotServerWithPack().bind(port);
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public void bind(int port) throws InterruptedException {
        // 创建NIO线程组（Reactor封装），用于处理网络事件
        // 处理客户端连接NIO线程组
        NioEventLoopGroup accetpNioEventLoopGroup = new NioEventLoopGroup();
        // 处理网络IO事件NIO线程组
        NioEventLoopGroup handleNioEventLoopGroup = new NioEventLoopGroup();

        try {
            // NIO服务启动辅助类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(accetpNioEventLoopGroup, handleNioEventLoopGroup)// 将线程组传递到group中
                .channel(NioServerSocketChannel.class)// 类似java nio中ServerSocketChannel
                .option(ChannelOption.SO_BACKLOG, 1024)// 设置TCP参数
                .childHandler(new MyChannelHandler());// 绑定IO事件处理类，类似java nio中的handler，主要用来处理网络IO事件

            // 绑定端口，然后调用同步阻塞方法
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println(
                "I,m a smart netty simple robot and wait for you ask. [I'm listen on port " + port + "]\n");
            // 等待链路关闭之后，才退出main函数
            channelFuture.channel().closeFuture().sync();
        }
        finally {
            // 优雅关闭退出
            accetpNioEventLoopGroup.shutdownGracefully();
            handleNioEventLoopGroup.shutdownGracefully();
        }

    }

    /**
     * IO事件处理类，类似java nio中的handler，主要用来处理网络IO事件
     *
     * @author tantexian
     * @since 2016/7/12
     * @params
     */
    class MyChannelHandler extends ChannelInitializer {
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(MyMarshallingFactory.buildMarshallingDecoder());
            channel.pipeline().addLast(MyMarshallingFactory.buildMarshallingEncoder());
            channel.pipeline().addLast(new StringDecoder());
            channel.pipeline().addLast(new SubReqServerHandle());
        }
    }
}
